<?php

namespace app\common\controller;

use app\common\model\CoinLog;
use EasyWeChat\Factory;
use Redis;
use Symfony\Component\Cache\Simple\RedisCache;
use think\Cache;
use think\Controller;
use think\Db;
use think\exception\HttpResponseException;
use think\Paginator;
use think\Response;

class Super extends Controller
{

    // 初始化
    protected function _initialize()
    {
        $this->assign("site_name", config("site.name"));
        $this->resurl = config("oss.resurl");
        $this->assign("resurl", $this->resurl);
        parent::_initialize();
    }

    protected function getwxwap($type = "default")
    {
        $config = [
            'app_id' => config("wxwap.appid"),
            'secret' => config("wxwap.appsecret"),
            'mch_id' => config("wxwap.mch_id"),
            'key' => config("wxwap.key"),   // API 密钥
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/api/user/waplogin',
            ],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/wechat.log',
            ],
        ];
        $cache = Cache::init();
        $redis = $cache->handler();
        $cache = new RedisCache($redis);
        if ($type == "default") {
            $app = Factory::officialAccount($config);
        }

        if ($type == "pay") {
            $app = Factory::payment($config);
        }

        $app['cache'] = $cache;
        return $app;

    }

    protected function getwxapp($type = "default")
    {
        $config = [
            'app_id' => config("wxapp.appid"),
            'secret' => config("wxapp.appsecret"),
            'mch_id' => config("wxapp.mch_id"),
            'key' => config("wxapp.key"),   // API 密钥
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/api/user/waplogin',
            ],
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/wechat.log',
            ],
        ];
        $cache = Cache::init();
        $redis = $cache->handler();
        $cache = new RedisCache($redis);
        if ($type == "default") {
            $app = Factory::miniProgram($config);
        }

        if ($type == "pay") {
            $app = Factory::payment($config);
        }

        $app['cache'] = $cache;
        return $app;

    }

    protected function filterdata($data, $filterlist)
    {
        foreach ($filterlist as $key => $val) {
            if (empty($data[$key])) {
                $this->e($filterlist[$key]);
            }
        }
    }

    protected function s($data = null)
    {
        $result = [
            'error_code' => 0,
            'result' => $data,
        ];
        return json($result);
    }

    protected function e($message, $error_code = 1)
    {
        $result = [
            'error_code' => $error_code,
            'message' => $message,
        ];
        $response = Response::create($result, 'json')->header([]);
        throw new HttpResponseException($response);
    }

    protected function autodata($filter = [])
    {
        $data = input("post.");
        $_data = [];
        foreach (array_keys($data) as $key) {
            if (isset($data[$key])) {
                $_data[$key] = $data[$key];
            }
        }
        return $_data;
    }

    protected function c($name, $val = null)
    {
        $config = model("config")->where("name", $name)->find();
        if (empty($val)) {
            if (empty($config)) {
                return null;
            }
            return json_decode($config['val'], true);
        }
        if (empty($config)) {
            model("config")->save(['name' => $name, 'val' => json_encode($val)]);
        } else {
            model("config")->save(['val' => json_encode($val)], ['name' => $name]);
        }

    }

    protected function coin($uid, $ccoin = null, $message = false)
    {
        $ccoin = intval($ccoin);
        $coin = model("coin")->where("uid", $uid)->lock(true)->find();
        if (empty($coin)) {
            model("coin")->insert(['uid' => $uid, "coin" => 0]);
            $coin = model("coin")->where("uid", $uid)->lock(true)->find();
        }
        if ($ccoin == null) {
            return intval($coin['coin']);
        }

        $befroe_coin = intval($coin['coin']);
        $after_coin = $befroe_coin + $ccoin;
        if ($after_coin < 0) {
            if ($message === false) {
                return "用户余额不足";
            }
            $this->e("用户余额不足");
        }
        if ($message === false) {
            return true;
        }
        try {

        } catch (\Exception $e) {
            throw new \Exception("积分操作异常");
        }
        $logdata = [];
        $logdata['uid'] = $uid;
        $logdata['before_coin'] = $befroe_coin;
        $logdata['change_coin'] = $ccoin;
        $logdata['after_coin'] = $after_coin;
        $logdata['time'] = now();
        $logdata['message'] = $message;
        $coinLog_m = new CoinLog();
        $coinLog_m->insert($logdata);
        model("coin")->update(['coin' => $after_coin], ['uid' => $uid]);
        return true;
    }

    function i($key, $message = "", $type = "string")
    {
        $val = input($key);
        if ($message !== "") {
            if (empty($val)) {
                $this->e($message);
            }
        }
        if($type==="string"){
            return $val;
        }
        if($type==="int"){
            return intval($val);
        }
        if($type==="float"){
            return floatval($val);
        }
    }


}
